<template>
  <van-list
    class="good-list"
    v-model:loading="state.loading"
    :finished="state.finished"
    finished-text="没有更多了"
    @load="onLoad"
    ref="vanList"
  >
    <van-cell
      class="good-list-cell"
      v-for="item in state.goodList"
      :key="item.goodsId"
      @click="detail(item.goodsId)"
    >
      <img :src="item.goodsCoverImg" alt="" />
      <span>{{ item.goodsName }}</span>
    </van-cell>
  </van-list>
</template>

<script>
import { getHomeGoods } from "@/network/home.js";
import _ from "loadsh";
export default {
  name: "GoodList",
  props: {
    tabIndex: Number,
  },
  data() {
    return {
      page: 0,
      state: {
        goodList: [],
        loading: false,
        finished: false,
      },
      goods: [
        {
          goodlist: [],
          page: 0,
        },
        {
          goodlist: [],
          page: 0,
        },
        {
          goodlist: [],
          page: 0,
        },
      ],
    };
  },
  created() {
    //初始化三个tab的内容
    for (let i = 0; i < 3; i++) {
      getHomeGoods(0, i).then((res) => {
        this.goods[i].goodlist = res;
      });
    }
    // 默认展示tab0
    this.state.goodList = [...this.goods[0].goodlist];
  },
  watch: {
    //切换tab
    tabIndex(now, before) {
      //将之前的展示数据更新到储存值中
      this.goods[before].page = this.page;
      this.goods[before].goodlist = [...this.state.goodList];
      //将之前储存的list和page赋值给展示用的list和page
      this.state.goodList = [...this.goods[now].goodlist];
      this.page = this.goods[now].page;
    },
  },
  // mounted() {
  //   this.$refs.vanList.addEventListener(
  //     "scroll",
  //     (e) => {
  //       console.log("父滚动条到页面顶部距离", e.target.offsetTop);
  //       console.log("相对距离", this.$refs.vanList.scrollTop);
  //       console.log("绝对距离", e.target.offsetTop + this.$refs.tree.scrollTop);
  //     },
  //     false
  //   );
  // },
  methods: {
    //上拉加载更多
    onLoad: _.throttle(function () {
      // 异步更新数据
      // console.log(this.state.finished);
      getHomeGoods(this.page, this.tabIndex).then((res) => {
        this.state.goodList.push(...res);
        if (res.length == 0) {
          this.state.finished = true;
        }
      });
      this.page++;
      // 加载状态结束
      this.state.loading = false;
    }, 2000),

    //跳转详情页
    detail(goodsId) {
      this.$router.push({
        path: "/details",
        query: {
          goodsId: goodsId,
        },
      });
    },
  },
};
</script>

<style scoped>
.good-list {
  display: flex;
  flex-wrap: wrap;
}
.good-list-cell {
  width: 50%;
  padding: 10px;
  box-sizing: border-box;
}
.good-list-cell img {
  width: 100%;
}
.good-list-cell span:hover {
  color: var(--color-high-text);
}
</style>
